import React, { useState, useEffect } from 'react';
import { connect } from 'umi';
import { Toast, Modal } from 'antd-mobile';
import { Spin } from 'antd';
import { router, withRouter } from 'umi';
import add from '@/components/Mobile/FileUploadMobile/icon-add.png';
import { useInterviewCandidate } from '@/pages/RecruitEmail/hooks';
import { pushRoute } from '@/pages/RecruitEmail/utils';
import { Button, Result, ApplyInfo, Picker, EditListItem, ListItem } from '../../components';
import { updateSalaryWill, submitInterviewResults, deleteBackgroundInfo } from '../../../service';
import styles from './index.less';

const InterviewCandidate = ({
    maxContactNum,
    showNotice,
    mobileBgArr,
    dispatch,
    needBackgroundFlag,
    nid,
    location
}) => {
    const { query } = location;

    const { data: talentInfo, loading, fetchDetail } = useInterviewCandidate(nid);

    const isEdit = talentInfo?.backgroundFlag !== 1;

    const [current, setCurrent] = useState();

    const [submitLoading, setSubmitLoading] = useState(false);

    useEffect(() => {
        if (!current) {
            const workStatus =
                isEdit && query?.workStatus
                    ? Number(query.workStatus)
                    : talentInfo?.recruitTalentBackgroundSalary?.lastPostStatus;
            setCurrent(isEdit ? workStatus : talentInfo?.recruitTalentBackgroundSalary?.lastPostStatus);
        }
        // 更新dva中背调联系人相关信息
        if (needBackgroundFlag && talentInfo) {
            dispatch({
                type: 'defaultBGList/initMobile',
                backgroundNum: 3,
                isEdit,
                recruitTalentBackgrounds: talentInfo?.recruitTalentBackgrounds || []
            });
        }
    }, [talentInfo]);

    const workStatusList = [
        { label: '在职', value: 1 },
        { label: '离职', value: 2 },
        { label: '应届生', value: 3 }
    ];

    const getWorkStatus = val => {
        let text = '';
        workStatusList.forEach(item => {
            if (item.value === val) {
                text = item.label;
            }
        });
        return text;
    };

    /**
     * 在切换成应届生时，清除原薪资
     */
    const clearCurrentSalary = () =>
        new Promise(resolve => {
            const params = {
                employId: talentInfo.employId,
                currentMonthSalary: 0,
                salaryProveRelations: []
            };
            updateSalaryWill(params).then(res => {
                const { code, msg } = res;
                if (code === 10000) {
                    resolve();
                } else {
                    Toast.info(msg); // 清空失败也继续往下走
                    resolve();
                }
            });
        });
    /**
     * 校验背调信息是否填报完成, true完成
     */
    const checkBackgroundFilled = () => {
        console.log(talentInfo?.recruitTalentBackgrounds);
        // 需要校验是否有没删除的默认数值
        for (let index = 0; index < mobileBgArr.length; index += 1) {
            const item = mobileBgArr[index];
            if (item.fakeId !== undefined) {
                console.log('还有默认值！！！');
                return false;
            }
        }
        // 其实走到这个函数，需要上传的联系人已经上传了,检查下从服务器拉下来的数据即可,
        if (talentInfo?.recruitTalentBackgrounds?.length > 0) {
            return true;
        }
        return false;
    };

    /**
     * 提交到服务器
     */
    const handleSubmit = () => {
        if (!current) {
            Toast.info('请选择工作状态');
        } else if (!talentInfo?.recruitTalentBackgroundSalary?.expectSalary) {
            Toast.info('请填写薪资意向');
        } else if (current !== 3 && needBackgroundFlag && !checkBackgroundFilled()) {
            Toast.info('请补全背调联系人信息');
        } else {
            Modal.alert(
                <div>
                    <div style={{ fontSize: 18, lineHeight: 1, paddingTop: 3 }}>确定提交？</div>
                    <div style={{ color: '#BCC1CD', marginTop: 12, fontSize: 14, lineHeight: 1 }}>
                        薪资意向信息无法二次修改
                    </div>
                </div>,
                '',
                [
                    { text: '取消' },
                    {
                        text: '确定',
                        onPress: () => {
                            const params = {
                                employId: talentInfo.employId,
                                lastPostStatus: current
                            };
                            setSubmitLoading(true);
                            submitInterviewResults(params)
                                .then(res => {
                                    const { code, msg } = res;
                                    if (code === 10000) {
                                        Toast.info('提交成功');
                                        fetchDetail(nid);
                                    } else {
                                        Toast.info(msg);
                                    }
                                })
                                .finally(() => {
                                    setSubmitLoading(false);
                                });
                        }
                    }
                ]
            );
        }
    };

    const title = isEdit
        ? '恭喜您通过面试！请提供您的薪资意向和其他必要信息'
        : '您已通过面试并提供相关信息，请耐心等待HR与您联系';

    const changeStatus = val => {
        if (val?.length && val?.[0] !== current) {
            Modal.alert(
                <div>
                    <div style={{ fontSize: 18, lineHeight: 1, paddingTop: 3 }}>确定切换工作状态？</div>
                    <div style={{ color: '#BCC1CD', marginTop: 12, fontSize: 14, lineHeight: 1 }}>
                        切换状态将清空你已填写的信息
                    </div>
                </div>,
                '',
                [
                    { text: '取消' },
                    {
                        text: '确定',
                        onPress: async () => {
                            setCurrent(val?.[0]);
                            if (val?.[0] === 3) {
                                await clearCurrentSalary();
                                if (talentInfo?.recruitTalentBackgrounds?.length === 0) {
                                    fetchDetail(nid);
                                }
                            }
                            if (val?.[0] === 3 && talentInfo?.recruitTalentBackgrounds?.length > 0) {
                                const params = {
                                    backgroundId: [],
                                    employId: talentInfo.employId
                                };
                                talentInfo.recruitTalentBackgrounds.forEach(item => {
                                    params.backgroundId.push(item.id);
                                });
                                deleteBackgroundInfo(params).then(res => {
                                    const { code, msg } = res;
                                    if (code === 10000) {
                                        Toast.info('清除成功');
                                        fetchDetail(nid);
                                    } else {
                                        Toast.info(msg);
                                    }
                                });
                            }
                            history.push({ query: { ...query, workStatus: val?.[0] } });
                        }
                    }
                ]
            );
        }
    };

    const showBackground = (itemId = -1, editIndex = -1) => {
        if (maxContactNum < mobileBgArr.length && itemId === -1) {
            // 限制添加上限
            console.log('限制添加上限');
            return;
        }
        if (isEdit && showNotice) {
            Modal.alert(
                <div>
                    <div style={{ fontSize: 18, lineHeight: '28px' }}>声明</div>
                    <div style={{ lineHeight: '24px', textAlign: 'left', fontSize: 14 }}>
                        添加背调联系人信息，即代表您已认真阅读并同意接受以下声明：
                    </div>
                    <div style={{ color: '#BCC1CD', lineHeight: '24px', textAlign: 'left', fontSize: 14 }}>
                        1.本人同意在入职前接受背调，并提供上级主管、平级同事或下属（若有）的联系方式。
                        <br />
                        2.公司可对有关的信息进行调查，亦有权查阅本人各种材料以及向第三方做个人访谈（如应聘者原雇主、家庭成员、业务联系人、经济来源人、朋友等）。
                        <br />
                        3.由于本人提供虚假信息的，公司方面有权在核实后随时终止劳动合同。
                    </div>
                </div>,
                '',
                [
                    { text: '取消' },
                    {
                        text: '我知道了',
                        onPress: () => {
                            dispatch({
                                type: 'defaultBGList/setShowNotice',
                                showNotice: false
                            });
                            pushRoute({
                                pathname: '/recruitment/register/background/contacts',
                                query: {
                                    ...query,
                                    nid,
                                    workStatus: current,
                                    itemId,
                                    editIndex
                                }
                            });
                        }
                    }
                ]
            );
        } else if (isEdit) {
            pushRoute({
                pathname: '/recruitment/register/background/contacts',
                query: {
                    ...query,
                    nid,
                    workStatus: current,
                    itemId,
                    editIndex
                }
            });
        }
    };

    /**
     * 渲染背调列表，背调添加按钮
     */
    const renderBackgroundList = () => {
        if (current !== 3 && needBackgroundFlag) {
            return (
                <>
                    <ListItem
                        title="背调联系人"
                        showArrow={isEdit && mobileBgArr.length === 0}
                        onClick={() => showBackground()}
                        // required={!isEdit}
                        extra={isEdit && mobileBgArr.length === 0 ? '待填写' : ''}
                        bordered={false}
                    >
                        {mobileBgArr.map((item, index) => (
                            <ListItem
                                titleStyle={{ paddingTop: 0, paddingBottom: 4, fontSize: 14 }}
                                title={item.objectName}
                                showArrow={isEdit}
                                extra={isEdit && Reflect.has(item, 'fakeId') ? '待填写' : ''}
                                bordered={false}
                                key={item.id + item.objectName}
                                onClick={() => showBackground(item.id, index)}
                            >
                                <div style={{ color: '#BCC1CD' }}>
                                    {item?.organizationName}
                                    {/* 若为添加的默认数据，则不显示关系，否则显示 */}
                                    {item.fakeId === undefined ? ` · ${item.relateType}` : ''}
                                </div>
                            </ListItem>
                        ))}
                    </ListItem>
                    {mobileBgArr.length > 0 && isEdit && maxContactNum > mobileBgArr.length ? (
                        <div
                            onClick={() => showBackground()}
                            style={{
                                display: 'flex',
                                justifyContent: 'center',
                                alignItems: 'center',
                                padding: '8px 0',
                                color: '#FFA22D',
                                fontSize: 16
                            }}
                        >
                            <img alt="" src={add} width="20" height="20" style={{ marginRight: 4 }} />
                            添加
                        </div>
                    ) : null}
                </>
            );
        }
        return null;
    };

    return (
        <div className={styles.interviewCandidateMobile}>
            <div className={styles.fakeItem} style={{ background: '#fff' }}></div>
            <Spin spinning={loading}>
                <div style={{ background: '#fff' }}>
                    <Result type={0} title={title} content=" " />
                </div>
                <div style={{ padding: '8px 16px 0 16px', background: '#fff' }}>
                    <ApplyInfo data={talentInfo?.recruitTalentBackgroundSalary} />
                </div>
                <div className={styles.fullDetail}>
                    {isEdit ? (
                        <Picker
                            title="工作状态"
                            data={workStatusList}
                            value={current ? [current] : []}
                            onChange={changeStatus}
                        >
                            <EditListItem title="工作状态">请选择</EditListItem>
                        </Picker>
                    ) : (
                        <ListItem title="工作状态" showArrow={false}>
                            <div>{getWorkStatus(talentInfo?.recruitTalentBackgroundSalary?.lastPostStatus)}</div>
                        </ListItem>
                    )}
                    <ListItem
                        title="薪资意向"
                        showArrow={isEdit}
                        onClick={() => {
                            if (isEdit) {
                                pushRoute({
                                    pathname: '/recruitment/register/background/intensions',
                                    query: {
                                        ...query,
                                        nid,
                                        workStatus: current
                                    }
                                });
                            }
                        }}
                        contentStyle={{
                            paddingBottom: 16
                        }}
                    >
                        {current !== 3 && (
                            <div>
                                原年薪{' '}
                                {talentInfo?.recruitTalentBackgroundSalary?.currentMonthSalary &&
                                talentInfo?.recruitTalentBackgroundSalary?.monthCount
                                    ? (
                                          talentInfo?.recruitTalentBackgroundSalary?.currentMonthSalary *
                                          talentInfo?.recruitTalentBackgroundSalary?.monthCount
                                      ).toFixed(0)
                                    : ''}{' '}
                                {talentInfo?.recruitTalentBackgroundSalary?.currentSalaryCurrencyCode}
                            </div>
                        )}
                        {current !== 3 &&
                            (!!talentInfo?.recruitTalentBackgroundSalary?.currentMonthSalary &&
                            !!talentInfo?.recruitTalentBackgroundSalary?.monthCount ? (
                                <div style={{ color: '#BCC1CD', marginTop: 5, marginBottom: 16 }}>
                                    {talentInfo?.recruitTalentBackgroundSalary?.currentMonthSalary} {' X '}
                                    {talentInfo?.recruitTalentBackgroundSalary?.monthCount}{' '}
                                    {talentInfo?.recruitTalentBackgroundSalary?.currentSalaryCurrencyCode}
                                </div>
                            ) : (
                                <div style={{ color: '#BCC1CD', marginTop: 5, marginBottom: 16 }}>待填写</div>
                            ))}
                        <div>
                            期望年薪 {talentInfo?.recruitTalentBackgroundSalary?.expectSalary || ''}{' '}
                            {talentInfo?.recruitTalentBackgroundSalary?.expectSalary &&
                                (talentInfo?.recruitTalentBackgroundSalary?.expectSalaryCurrencyCode ||
                                    talentInfo?.recruitTalentBackgroundSalary?.companyCurrencyCode)}
                        </div>
                        {!!talentInfo?.recruitTalentBackgroundSalary?.expectSalary &&
                        !!talentInfo?.recruitTalentBackgroundSalary?.expectMonthNumber ? (
                            <div style={{ color: '#BCC1CD', marginTop: 5 }}>
                                {(
                                    talentInfo?.recruitTalentBackgroundSalary?.expectSalary /
                                    talentInfo?.recruitTalentBackgroundSalary?.expectMonthNumber
                                ).toFixed(0)}{' '}
                                {' X '}
                                {talentInfo?.recruitTalentBackgroundSalary?.expectMonthNumber}{' '}
                                {talentInfo?.recruitTalentBackgroundSalary?.expectSalaryCurrencyCode ||
                                    talentInfo?.recruitTalentBackgroundSalary?.companyCurrencyCode}
                            </div>
                        ) : (
                            <div style={{ color: '#BCC1CD', marginTop: 5 }}>待填写</div>
                        )}
                    </ListItem>
                    {renderBackgroundList()}
                </div>
                {talentInfo && isEdit && (
                    <div className={styles.pageFooter}>
                        <Button type="primary" loading={submitLoading} onClick={handleSubmit}>
                            提交
                        </Button>
                    </div>
                )}
            </Spin>
            {/* <Modal
                visible={visible}
                transparent
                maskClosable={false}
                onClose={() => setVisible(false)}
                title={null}
                className="backgroundModal"
                footer={[
                    {
                        text: 'Ok',
                        onPress: () => {
                            console.log('ok');
                            setVisible(false);
                        }
                    }
                ]}
            >
                <BackgroundIntensions
                    // query={query}
                    workStatus={current}
                    talentInfo={talentInfo}
                    closeModal={() => setVisible(false)}
                    submit={() => fetchDetail(nid)}
                />
            </Modal> */}
            {/* <Modal
                visible={visibleContacts}
                transparent
                maskClosable={false}
                onClose={() => setVisibleContacts(false)}
                title={null}
                className="backgroundModal"
                footer={[
                    {
                        text: 'Ok',
                        onPress: () => {
                            console.log('ok');
                            setVisibleContacts(false);
                        }
                    }
                ]}
            >
                <BackgroundContacts
                    bitem={bitem}
                    query={query}
                    talentInfo={talentInfo}
                    closeModal={() => setVisibleContacts(false)}
                    submit={() => fetchDetail(nid)}
                />
            </Modal> */}
        </div>
    );
};

export default withRouter(
    connect(({ defaultBGList }) => ({
        ...defaultBGList
    }))(InterviewCandidate)
);
